package cn.edu.ujn.ch16.c;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {
	@GetMapping("/upload")
	public String toUpload() {
		return "fileUpload";
	}
	@GetMapping("/toDownload")
	public String toDownload() {
		return "download";
	}
	@PostMapping("/fileUpload")
	public String upload(String name,List<MultipartFile> uploadfile,HttpServletRequest request) {
		for(MultipartFile mfile:uploadfile) {
			String filename = mfile.getOriginalFilename();
			String contentType = mfile.getContentType();
			System.out.println(contentType);
			filename=name+"_"+UUID.randomUUID()+"_"+filename;
			String path = request.getServletContext().getRealPath("/upload/");
			System.out.println(path);
			File file = new File(path+filename);
			try {
				mfile.transferTo(file);
			} catch (IllegalStateException | IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
				return "error";
			}
		}
		return "success";
	}
	@RequestMapping("/download")
	public ResponseEntity<byte[]> download(String filename,HttpServletRequest request) throws IOException{
		String realPath = request.getServletContext().getRealPath("/upload/");
		File file = new File(realPath+File.separator+filename);
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.setContentDispositionFormData("attachment", filename);
		httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders,200);
		return responseEntity;
		
	}
}
